#!/usr/bin/env python
# spritesheet.py

# usage
"""
import spritesheet
...
ss = spritesheet.spritesheet('somespritesheet.png')
# Sprite is 16x16 pixels at location 0,0 in the file...
image = ss.image_at((0, 0, 16, 16))
images = []
# Load two images into an array, their transparent bit is (255, 255, 255)
images = ss.images_at((0, 0, 16, 16),(17, 0, 16,16), colorkey=(255, 255, 255))
...
"""
#

import pygame

# spritesheet class
# @params {string} filename
class spritesheet(object):

    # initialize spritesheet
    # @params {string} filename
    def __init__(self, filename):

        try:
            self.sheet = pygame.image.load(filename).convert()
        except pygame.error, message:
            print "Unable to load spritesheet image:", filename
            raise SystemExit, message

    # Load a specific image from a specific rectangle
    # @params {tuple} rectangle
    # @params {integer} colorkey
    # @return {object} image
    def image_at(self, rectangle, colorkey=None):

        """Loads image from x, y, x+offset, y+offset"""
        rect = pygame.Rect(rectangle)
        image = pygame.Surface(rect.size).convert()
        image.blit(self.sheet, (0, 0), rect)
        if colorkey is not None:
            if colorkey is -1:
                colorkey = image.get_at((0, 0))
            image.set_colorkey(colorkey, pygame.RLEACCEL)
        return image

    # Load a whole bunch of images and return them as a list
    # @params {tuple} rectangles separated with kommatas
    # @params {integer} colorkey
    # @return {list} images
    def images_at(self, rects, colorkey=None):

        """Loads multiple images, supply a list of coordinates"""
        return [self.image_at(rect, colorkey) for rect in rects]

    # Load a whole strip of images
    # @params {tuple} rectangle
    # @return {list} strip images
    def load_strip(self, rect, image_count, colorkey=None):

        """Loads a strip of images and returns them as a list"""
        tups = [(rect[0] + rect[2] * x, rect[1], rect[2], rect[3])
                for x in range(image_count)]
        return self.images_at(tups, colorkey)

########
# test #
########
# img = spritesheet("img/spritesheet.png")
